<?php

namespace app\apisell\controller\admin;

use app\BaseController;
use app\common\utils\Res;
use think\facade\Db;

class UserPay extends BaseController
{
    /**
     * 提现审批
     */
    public function getUserPayList()
    {
        $userid = $this->request->userName;
        $param = $this->request->param();
        $size = $param['pageSize'] ? $param['pageSize'] : 10;  //每页显示条数
        $page = $param['pageNumber'] ? $param['pageNumber'] : 1;  //当前页数
        $applyForTime = $param['apply_for_time']??false;
        $status = $param['status']??false;
        $popuname = $param['popu_name']??false;
        $where = array();
       
        if ($status) {
            $where[] = array('p.status', '=', $status);
        }
        if ($applyForTime) {
            $where[] = array('p.apply_for_time', 'like', '%' . $applyForTime . '%');
        }
        if ($popuname) {
            $where[] = array('pu.popu_name', 'like', '%' . $popuname . '%');
        }
        //创建时间
        if (isset($param["add_time"]) && !empty($param["add_time"])) {
            $where[] = ["p.apply_for_time", '>', $param["add_time"][0]];
            $where[] = ["p.apply_for_time", '<=', $param["add_time"][1]];
        }
        //查询提现审批
        $result = Db::table('xh_sell_user_pay')->alias('p')
            ->field('p.*, pu.popu_name,u.money_balance')
            ->leftJoin('xh_sell_user u','p.user_id = u.id')
            ->leftJoin('xh_sell_popu_user pu','u.id = pu.popu_user_id')
            ->where($where)
            ->page($page, $size)
            ->select()->toArray();
        
        foreach ($result as $key => $value) {
            //申请状态
            switch ($value['status']) {
                case 1: $result[$key]['stype'] = '申请中'; break;
                case 2: $result[$key]['stype'] = '已通过'; break;
                case 3: $result[$key]['stype'] = '已拒绝'; break;
                case 4: $result[$key]['stype'] = '打款中'; break;
                case 5: $result[$key]['stype'] = '打款失败'; break;
                case 6: $result[$key]['stype'] = '已到账'; break;
            }
            $result[$key]['money'] = round($value['money'] / 100,2);
            $result[$key]['money_balance'] = round($value['money_balance'] / 100,2);
        }
        
        $count = Db::table('xh_sell_user_pay')->alias('p')
            ->field('p.*, pu.popu_name,u.money_balance')
            ->leftJoin('xh_sell_user u','p.user_id = u.id')
            ->leftJoin('xh_sell_popu_user pu','u.id = pu.popu_user_id')
            ->where($where)
            ->count();
        $data = [
            'list' => $result,
            'total' => $count
        ];
        return Res::ok($data);
    }

    /**
     * 拒绝申请
     */
    public function refuseApply()
    {
        $param = $this->request->param();
        Db::startTrans();
        try {
            $userPay = Db::table('xh_sell_user_pay')->where(['id' => $param['id']])->find();
            if ($userPay) {
                //更改提现审批状态
                Db::table('xh_sell_user_pay')->where(['id' => $param['id']])->update(['status' => 3]);
                //更改用户表
                $user = Db::table('xh_sell_user')->where(['id' => $userPay['user_id']])->find();
                $old_await = $user['money_pay_await'];
                $old_loading = $user['money_pay_loading'];
                $nwe_await = $old_await + $userPay['money'];
                $new_loading = $old_loading - $userPay['money'];
                Db::table('xh_sell_user')->where(['id' => $userPay['user_id']])->update(['money_pay_await' => $nwe_await, 'money_pay_loading' => $new_loading]);
                
                //添加审批记录
                $logData = [
                    'user_pay_id' => $param['id'],
                    'type' => 3,
                    'desc' => '你已达到当日提现次数上限，请明天再进行提现。',
                    'remark' => $param['remark'],
                    'change_json' => '[{"field":"money_pay_await","former":'.$old_await.',"after":'.$nwe_await.'},{"field":"money_pay_loading","former":'.$old_loading.',"after":'.$new_loading.'}]',
                    'change_time' => date('Y-m-d H:i:s',time()),
                    'operate_id' => ''
                ];
                Db::table('xh_sell_user_pay_log')->insert($logData);
            }else {
                return Res::error('未查到该条提现记录');
            }
            Db::commit();
            return Res::ok();
        }catch (Exception $e) {
            Db::rollback();
            // 记录错误日志
            error_log($e->getMessage());
            return Res::error('拒绝申请失败');
        }
       
    }

    /**
     * 拒绝申请
     */
    public function passApply()
    {
        $param = $this->request->param();
        Db::startTrans();
        try {
            $userPay = Db::table('xh_sell_user_pay')->where(['id' => $param['id']])->find();
            if ($userPay) {
                //更改提现审批状态
                Db::table('xh_sell_user_pay')->where(['id' => $param['id']])->update(['status' => 2,'voucher' => $param['voucher']]);
                //更改用户表
                $user = Db::table('xh_sell_user')->where(['id' => $userPay['user_id']])->find();
                $old_balance = $user['money_balance'];
                $old_loading = $user['money_pay_loading'];
                $nwe_balance = $old_balance - $userPay['money'];
                $new_loading = $old_loading - $userPay['money'];
                Db::table('xh_sell_user')->where(['id' => $userPay['user_id']])->update(['money_balance' => $nwe_balance, 'money_pay_loading' => $new_loading]);
                
                $popuUser = Db::table('xh_sell_popu_user')->where(['popu_user_id' => $user['id']])->find();
                //添加审批记录
                $logData = [
                    'user_pay_id' => $param['id'],
                    'type' => 6,
                    'desc' => '【'.$popuUser['popu_name'].'】 于 【'.date('Y-m-d',time()).'】 到账 【微信零钱】，【'.round($userPay['money'] / 100,2).'】元。',
                    'change_json' => '[{"field":"money_balance","former":'.$old_balance.',"after":'.$nwe_balance.'},{"field":"money_pay_loading","former":'.$old_loading.',"after":'.$new_loading.'}]',
                    'change_time' => date('Y-m-d H:i:s',time()),
                    'operate_id' => ''
                ];
                Db::table('xh_sell_user_pay_log')->insert($logData);
            }else {
                return Res::error('未查到该条提现记录');
            }
            Db::commit();
            return Res::ok();
        }catch (Exception $e) {
            Db::rollback();
            // 记录错误日志
            error_log($e->getMessage());
            return Res::error('通过申请失败');
        }

    }
    
    /**
     * 提现审批记录
     */
    public function getUserPayRecord()
    {
        $size = $param['size'] ?? 10;
        $param = $this->request->param();
        $map = [];
        if (isset($param["operate_time"]) && !empty($param["operate_time"])) {
            $map[] = ["sup.operate_time", 'between', $param["operate_time"]];
        }
        if (isset($param["status"]) && $param["status"] != '') {
            $map["sup.status"] = $param["status"];
        }else{
            $map[] = ['sup.status', 'in', [2,3]];
        }
        if (isset($param["operate_name"]) && !empty($param["operate_name"])) {
            $map[] = ["m.user_name", 'like', '%' . $param["operate_name"] . '%'];
        }
        $fields = 'sup.status,sup.operate_time,m.user_name as operate_name,u.nickname';
        
        
        $result = Db::table('xh_sell_user_pay')
            ->alias('sup')
            ->leftJoin('xh_siyu_sys_member m','m.uid = sup.operate_id')
            ->leftJoin('xh_sell_user u','sup.user_id = u.id')
            ->where($map)
            ->field($fields)
            ->order('sup.id desc')
            ->paginate($size);
        return Res::ok($result);
    }
    
}